package com.beverages.holder.controller;

import com.beverages.holder.client.MerchantCommoditiesClient;
import com.beverages.holder.client.MerchantMessagesClient;
import com.beverages.holder.client.MerchantOrdersClient;
import com.beverages.holder.common.Result;
import com.beverages.holder.entity.Holder;
import com.beverages.holder.entity.dto.intermediate.CommoditiesDTO;
import com.beverages.holder.entity.dto.HoldersDTO;
import com.beverages.holder.entity.dto.intermediate.OrdersDTO;
import com.beverages.holder.service.IHolderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/merchant/holder")
public class HolderController {

    @Resource
    private IHolderService holderService;

    @Autowired
    private MerchantOrdersClient merchantOrdersClient;

    @Autowired
    private MerchantCommoditiesClient merchantCommoditiesClient;

    @Autowired
    private MerchantMessagesClient merchantMessagesClient;

    @GetMapping("list")
    public Result<List<Holder>> listAllHolders(){
        return Result.success(holderService.list());
    }

    @GetMapping("/preset")
    public Result presetPreparedOrders() {
        holderService.updatePreparedOrderIds();
        this.getBeveragesWhichArePrepared();
        return Result.success();
    }

    @GetMapping("/processing/{holderId}")
    public Result setOneProcessingBeverage(@PathVariable("holderId") Integer holderId) {
        Holder processingHolder = holderService.getById(holderId);
        Integer processingOrderId = processingHolder.getWaitingOrderId();
        processingHolder.setProcessingOrderId(processingOrderId);
        merchantOrdersClient.updateCompletionStatus(processingOrderId, 2);
        processingHolder.setWaitingOrderId(0);
        holderService.updateById(processingHolder);
        return Result.success();
    }

    @GetMapping("/prepared")
    public synchronized Result getBeveragesWhichArePrepared() {
        List<Holder> holders = holderService.getHoldersWhichHavePreparedOrder();
        List<OrdersDTO> preparedOrderDTOs = new ArrayList<>();
        for (Holder holder : holders){
            Integer preparedOrderIdOfThisHolder = holder.getPreparedOrderId();
            if(!preparedOrderIdOfThisHolder.equals(0)){
                preparedOrderDTOs.add(merchantOrdersClient.findOneOrderDTO(preparedOrderIdOfThisHolder).getData());
            }
        }

        List<CommoditiesDTO> commodityDTOs = new ArrayList<>();
        for (OrdersDTO ordersDTO : preparedOrderDTOs){
            commodityDTOs.add(merchantCommoditiesClient.findOneCommodityDTO(ordersDTO.getMilkteaId()).getData());
        }

        List<HoldersDTO> holderDTOs = new ArrayList<>(holders.size());
        for (int i = 0; i < holders.size(); i++) {
            HoldersDTO holderDTO = new HoldersDTO();

            Holder currentHolder = holders.get(i);

            holderDTO.setHolderId(currentHolder.getId());
            holderDTO.setPreparedOrderId(currentHolder.getPreparedOrderId());

            currentHolder.setWaitingOrderId(currentHolder.getPreparedOrderId());
            currentHolder.setPreparedOrderId(0);
            holderService.updateById(currentHolder);

            holderDTO.setMilkteaName(commodityDTOs.get(i).getMilkteaName());
            holderDTO.setIngredients(commodityDTOs.get(i).getIngredients());
            holderDTO.setSugarLevel(preparedOrderDTOs.get(i).getSugarLevel());
            holderDTO.setIceLevel(preparedOrderDTOs.get(i).getIceLevel());
            holderDTO.setToppings(preparedOrderDTOs.get(i).getToppings());

            holderDTOs.add(holderDTO);
//            holders.get(i).setWaitingOrderId(holders.get(i).getPreparedOrderId());
//            holders.get(i).setPreparedOrderId(0);
//            holderService.updateById(holders.get(i));
        }
        System.out.println("holderDTOs:"+holderDTOs);
        merchantMessagesClient.sendPreparedOrdersToFacility(holderDTOs);
        return Result.success(holderDTOs);
    }

    @GetMapping("/full/{holderId}")
    public Result updateFullHolder(@PathVariable("holderId") Integer holderId){
        Holder processedHolder = holderService.getById(holderId);

        //单个已做完奶茶的订单id
        Integer singleOrderIdWithCompletedBeverage = processedHolder.getProcessingOrderId();
        processedHolder.setOrderId(singleOrderIdWithCompletedBeverage);
        processedHolder.setProcessingOrderId(0);
        merchantOrdersClient.fillHolderIds(singleOrderIdWithCompletedBeverage, holderId);
        holderService.updateById(processedHolder);

        //当前所有在置物格上准备做或制作中的订单
        List<Integer> currentAllWaitingOrProcessingOrdersInHolder = new ArrayList<>();
        List<Holder> allCurrentHolders = this.listAllHolders().getData();
        for(Holder singleHolder : allCurrentHolders){
            Integer currentWaitingOrderIdInThisHolder = singleHolder.getWaitingOrderId();
            Integer currentProcessingOrderIdInThisHolder = singleHolder.getProcessingOrderId();
            if(!currentWaitingOrderIdInThisHolder.equals(0)){  //添加等待中的订单在集合中
                currentAllWaitingOrProcessingOrdersInHolder.add(currentWaitingOrderIdInThisHolder);
            }else if(!currentProcessingOrderIdInThisHolder.equals(0)){  //添加制作中的订单在集合中
                currentAllWaitingOrProcessingOrdersInHolder.add(currentProcessingOrderIdInThisHolder);
            }
        }

        //  该订单所有奶茶已制作完毕
        if(!currentAllWaitingOrProcessingOrdersInHolder.contains(singleOrderIdWithCompletedBeverage)){
            System.out.println("singleOrderIdWithCompletedBeverage:"+singleOrderIdWithCompletedBeverage);
            merchantOrdersClient.updateCompletionStatus(singleOrderIdWithCompletedBeverage, 3);
        }


        /*
        //单个已做完奶茶的订单id
        Integer singleOrderIdWithCompletedBeverage = holder.getPreparedOrderId();
        holder.setOrderId(singleOrderIdWithCompletedBeverage);
        holder.setPreparedOrderId(0);
        merchantOrdersClient.fillHolderIds(holder.getOrderId(), holderId);
        holderService.updateById(holder);

        //当前所有在置物格上准备的订单
        List<Integer> currentAllPreparedOrdersInHolder = new ArrayList<>();
        List<Holder> allCurrentHolders = this.listAllHolders().getData();
        for(Holder singleHolder : allCurrentHolders){
            Integer currentPreparedOrderIdInThisHolder = singleHolder.getPreparedOrderId();
            if(!currentPreparedOrderIdInThisHolder.equals(0)){
                currentAllPreparedOrdersInHolder.add(currentPreparedOrderIdInThisHolder);
            }
        }
        System.out.println("currentPreparedOrderIdInThisHolder:"+currentAllPreparedOrdersInHolder);

        //  该订单所有奶茶已制作完毕
        if(!currentAllPreparedOrdersInHolder.contains(singleOrderIdWithCompletedBeverage)){
            System.out.println("singleOrderIdWithCompletedBeverage:"+singleOrderIdWithCompletedBeverage);
            merchantOrdersClient.updateCompletionStatus(singleOrderIdWithCompletedBeverage, 3);
        }
*/








//        for(Integer orderId : currentAllPreparedOrdersInHolder){
//            if(!currentAllPreparedOrdersInHolder.contains(singleOrderIdWithCompletedBeverage)){
//                merchantOrdersClient.updateCompletionStatus(singleOrderIdWithCompletedBeverage, 3);
//            }
//        }


//        List<Holder> allCurrentHolders = this.listAllHolders().getData();
//        List<Integer> currentPreparedOrderIds = new ArrayList<>();
//        for(Holder currentHolder : allCurrentHolders){
//            currentPreparedOrderIds.add(currentHolder.getPreparedOrderId());
//        }
        //  该订单所有奶茶已制作完毕
//        if(!currentPreparedOrderIds.contains(holder.getOrderId())){
//            merchantOrdersClient.updateCompletionStatus(holder.getOrderId(),3);
//        }


        return Result.success();
    }

    @PostMapping("/pick-up")
    public Result updateHoldersFromWhichBeverageWasJustTaken(@RequestBody List<Integer> holderIds){
//        Holder holder = holderService.getById(holderId);
//        merchantOrdersClient.updatepPlaceStatus(holder.getOrderId(),1);
//        holder.setOrderId(0);
//        holderService.updateById(holder);

        //被取走饮料的置物格
        List<Holder> takenHolders = new ArrayList<>();
        for (Integer holderId : holderIds){
            takenHolders.add(holderService.getById(holderId));
        }

        //被取走饮料的置物格上的订单
        List<Integer> ordersInTakenHolders = new ArrayList<>();
        for (Holder holder : takenHolders){
            ordersInTakenHolders.add(holder.getOrderId());
            merchantOrdersClient.emptyHolderIds(holder.getOrderId(), holder.getId());
            holder.setOrderId(0);
            holderService.updateById(holder);
        }

        //当前所有在置物格上的订单
        List<Integer> currentAllOrdersInHolder = new ArrayList<>();
        List<Holder> allCurrentHolders = this.listAllHolders().getData();
        for(Holder holder : allCurrentHolders){
            Integer currentOrderIdInThisHolder = holder.getOrderId();
            if(!currentOrderIdInThisHolder.equals(0)){
                currentAllOrdersInHolder.add(currentOrderIdInThisHolder);
            }
        }

        // 该订单所有饮料被取完了
        for(Integer orderId : ordersInTakenHolders){
            if(!currentAllOrdersInHolder.contains(orderId)){
                merchantOrdersClient.updatepPlaceStatus(orderId, 1);
            }
        }




//        System.out.println("updateHoldersFromWhichBeverageWasJustTaken has been invoked");
//        for (Integer holderId : holderIds) {
//            Holder holder = holderService.getById(holderId);
//            Integer orderIdInCurrentHolder = holder.getOrderId();
//            // 清除 holder 的 orderId
//            holder.setOrderId(0);
//            System.out.println("orderIdInCurrentHolder:"+orderIdInCurrentHolder);
//            merchantOrdersClient.emptyHolderIds(orderIdInCurrentHolder, holderId);
//            // 更新 holder 信息
//            holderService.updateById(holder);
//
//            List<Holder> allCurrentHolders = this.listAllHolders().getData();
//            List<Integer> currentOrderIds = new ArrayList<>();
//            for(Holder currentHolder : allCurrentHolders){
//                currentOrderIds.add(currentHolder.getOrderId());
//            }
//
//            // 该订单所有饮料被取完了
//            if(!currentOrderIds.contains(orderIdInCurrentHolder)){
//                merchantOrdersClient.updatepPlaceStatus(orderIdInCurrentHolder, 1);
//            }
//
//
//        }
        this.presetPreparedOrders();
        return Result.success();
    }

}